<template>
  <el-tabs v-model="activePath" type="card" editable @edit="closeTabFun" @tab-click="() => tabClickFun(activePath)">
    <el-tab-pane v-for="item in tabList" :key="item.path" :label="item.title" :name="item.path" />
  </el-tabs>
</template>

<script lang="ts" setup>
  import router from '@/router'
  import { computed, onMounted, ref, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { useKeepAliveStore, useMenuStore } from '@/store'
  const keepAliveStore = useKeepAliveStore()
  const menuStore = useMenuStore()
  const route = useRoute()
  const menuList = computed(() => menuStore.getMenuList)
  const tabList = ref<any[]>([])
  onMounted(() => {
    tabList.value = []
    tabList.value.push({
      title: '首页',
      closable: false,
      path: '/',
    })
    activePath.value = '/'
    formatTabsFun()
  })
  // 监听store的是修改数据时,store内数据会改变
  //   const userData = computed((): CurrentUserResult => JSON.parse(JSON.stringify(keepAliveStore.getKeepAliveList)))
  const activePath = ref(tabList.value.length > 0 ? tabList.value[0].path : '')
  const closeTabFun = (targetPath: string, action: 'remove' | 'add') => {
    if (action === 'remove') {
      let lastIndex = 0
      tabList.value.forEach((pane, i) => {
        if (pane.path === targetPath) {
          lastIndex = i - 1
        }
      })
      tabList.value = tabList.value.filter((pane) => pane.path !== targetPath)
      if (tabList.value.length && activePath.value === targetPath) {
        if (lastIndex >= 0) {
          activePath.value = tabList.value[lastIndex].path
        } else {
          activePath.value = tabList.value[0].path
        }
        tabClickFun(activePath.value)
      }
    }
  }
  // 跳转方法
  const tabClickFun = (path: any) => {
    const oldUrl = route.path.split('/')[1]
    const toUrl = path.split('/')[1]
    if (path === '/') {
      router.push(path)
    } else if (oldUrl === toUrl) {
      router.replace(path)
    } else {
      router.push(path)
    }
  }
  const formatTabsFun = () => {
    const isExist = tabList.value.some((item) => item.path === route.path)
    if (route.path !== '/' && !isExist && menuList.value) {
      const targetInfo = menuList.value.find((el: { href: string }) => el.href === route.path)
      if (targetInfo) {
        tabList.value.push({
          title: targetInfo.menuName,
          closable: true,
          path: route.path,
          templateName: targetInfo.href.substring(1, targetInfo.href.length).replace(/\//g, '_'),
        })
        activePath.value = route.path
      }
    } else if (isExist) {
      activePath.value = route.path
    }
    keepAliveStore.setKeepAliveList(tabList.value.filter((item) => item && item.templateName).map((item) => item.templateName))
  }
  watch(
    () => route.path,
    () => {
      formatTabsFun()
    },
  )
</script>

<style lang="less" scoped>
  :deep(.el-tabs__new-tab) {
    display: none;
  }
</style>
